using System;
using System.IO;
using System.Text;

namespace SanmaoTools.Services
{
    public class LogService
    {
        private readonly string _logFilePath;
        private readonly object _lockObject = new object();

        public LogService(string logFilePath = "logs/app.log")
        {
            _logFilePath = logFilePath;
            EnsureLogDirectoryExists();
        }

        private void EnsureLogDirectoryExists()
        {
            var directory = Path.GetDirectoryName(_logFilePath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
        }

        public void LogInformation(string message)
        {
            WriteLog("INFO", message);
        }

        public void LogWarning(string message)
        {
            WriteLog("WARN", message);
        }

        public void LogError(string message)
        {
            WriteLog("ERROR", message);
        }

        public void LogDebug(string message)
        {
            WriteLog("DEBUG", message);
        }

        private void WriteLog(string level, string message)
        {
            var logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{level}] {message}{Environment.NewLine}";
            lock (_lockObject)
            {
                try
                {
                    File.AppendAllText(_logFilePath, logMessage, Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    // 如果写入日志失败，尝试写入到备用日志文件
                    var backupLogPath = Path.Combine(
                        Path.GetDirectoryName(_logFilePath),
                        $"app_backup_{DateTime.Now:yyyyMMddHHmmss}.log"
                    );
                    File.AppendAllText(backupLogPath, logMessage, Encoding.UTF8);
                    File.AppendAllText(backupLogPath, $"日志写入错误: {ex.Message}{Environment.NewLine}", Encoding.UTF8);
                }
            }
        }
    }
} 